Skip to content

feat: attachments #15000

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 36 commits into from
May 14, 2025
Merged

feat: attachments #15000

merged 36 commits into from
May 14, 2025

Conversation

Rich-Harris
Copy link
Member

@Rich-Harris Rich-Harris commented Jan 13, 2025

What?

This PR introduces attachments, which are essentially a more flexible and modern version of actions.

Why?

Actions are neat but they have a number of awkward characteristics and limitations:

  • the syntax is very weird! <div use:foo={bar}> implies some sort of equality between foo and bar but actually means foo(div, bar). There's no way you could figure that out just by looking at it
  • the foo in use:foo has to be an identifier. You can't, for example, do use:createFoo() — it must have been declared elsewhere
  • as a corollary, you can't do 'inline actions'
  • it's not reactive. If foo changes, use:foo={bar} does not re-run. If bar changes, and foo returned an update method, that method will re-run, but otherwise (including if you use effects, which is how the docs recommend you use actions) nothing will happen
  • you can't use them on components
  • you can't spread them, so if you want to add both attributes and behaviours you have to jump through hoops

We can do much better.

How?

You can attach an attachment to an element with the {@attach fn} tag (which follows the existing convention used by things like {@html ...} and {@render ...}, where fn is a function that takes the element as its sole argument:

<div {@attach (node) => console.log(node)}>...</div>

This can of course be a named function, or a function returned from a named function...

<button {@attach tooltip('Hello')}>
  Hover me
</button>

...which I'd expect to be the conventional way to use attachments.

Attachments can be create programmatically and spread onto an object:

<script>
  const stuff = {
    class: 'cool-button',
    onclick: () => console.log('clicked'),
    [Symbol()]: (node) => alert(`I am a ${node.nodeName}`)
  };
</script>

<button {...stuff}>hello</button>

As such, they can be added to components:

<Button
  class="cool-button"
  onclick={() => console.log('clicked')}
  {@attach (node) => alert(`I am a ${node.nodeName}`)}
>
  hello
</Button>
<script>
  let { children, ...props } = $props();
</script>

<button {...props}>{@render children?.()}</button>

Since attachments run inside an effect, they are fully reactive.

I haven't figured out if it should be possible to return a cleanup function directly from an attachment, or if you should need to create a child effect

Because you can create attachments inline, you can do cool stuff like this, which is somewhat more cumbersome today.

When?

As soon as we bikeshed all the bikesheddable details.


While this is immediately useful as a better version of actions, I think the real fun will begin when we start considering this as a better version of transitions and animations as well. Today, the in:/out:/transition: directives are showing their age a bit. They're not very composable or flexible — you can't put them on components, they generally can't 'talk' to each other except in very limited ways, you can't transition multiple styles independently, you can't really use them for physics-based transitions, you can only use them on DOM elements rather than e.g. objects in a WebGL scene graph, and so on.

Ideally, instead of only having the declarative approach to transitions, we'd have a layered approach that made that flexibility possible. Two things in particular are needed: a way to add per-element lifecycle functions, and an API for delaying the destruction of an effect until some work is complete (which outro transitions uniquely have the power to do today). This PR adds the first; the second is a consideration for our future selves.

Before submitting the PR, please make sure you do the following

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • Prefix your PR title with feat:, fix:, chore:, or docs:.
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.
  • If this PR changes code within packages/svelte/src, add a changeset (npx changeset).

Tests and linting

  • Run the tests with pnpm test and lint the project with pnpm lint

Copy link

changeset-bot bot commented Jan 13, 2025

🦋 Changeset detected

Latest commit: 8255bc6

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
svelte Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@Rich-Harris
Copy link
Member Author

preview: https://svelte-dev-git-preview-svelte-15000-svelte.vercel.app/

this is an automated message

Copy link
Contributor

Playground

pnpm add https://pkg.pr.new/svelte@15000

@huntabyte
Copy link
Member

Would something like this work as well?

<script>
  	import { createAttachmentKey } from 'svelte/attachments';

  	const stuff = {
    	class: 'cool-button',
    	onclick: () => console.log('clicked'),
    	[createAttachmentKey()]: (node) => console.log(`I am one attachment`)
  	};

	const otherStuff = {
		[createAttachmentKey()]: (node) => console.log('I am another attachment')
	}
</script>

<button {...stuff} {...otherStuff}>hello</button>

Where the result on mount would be:

I am one attachment
I am another attachment

@JonathonRP
Copy link

Personally I would prefer a createAttachment like createSnippet. Just something to consider for the team

@Leonidaz
Copy link
Contributor

nice! 👍

I wonder if it would be more flexible for composition if the syntax can work with named props.

programmatically:

<script>
  // reverse logic instead of symbol-ed key, a symbol-ed function wrapper
  import { createAttachment } from 'svelte/attachments';

  const stuff = {
    class: 'cool-button',
    onclick: () => console.log('clicked'),
    showAlert: createAttachment((node) => alert(`I am a ${node.nodeName}`)),
    logger: createAttachment((node) => console.log(`I am a ${node.nodeName}`)),
  };
</script>

<button {...stuff}>hello</button>

directly on components:

<Button
  class="cool-button"
  onclick={() => console.log('clicked')}
  showAlert={@attach (node) => alert(`I am a ${node.nodeName}`)}
  logger={@attach (node) => console.log(`I am a ${node.nodeName}`)}
>
  hello
</Button>

and spread in which case at runtime the prop values can be checked for a special attach symbol (the prop key names are irrelevant)

<script>
  let { children, ...props } = $props();
</script>

<button {...props}>{@render children?.()}</button>

or explicitly declare props, for further composition (and it would be nice for TypeScript declarations):

<script>
  import AnotherComponent from './AnotherComponent.svelte';
  let { children, showAlert, logger } = $props();
</script>

<button {@attach showAlert} {@attach logger}>{@render children?.()}</button>

<AnotherComponent logger={@attach logger} />

And with either syntax, one could also just pass in a prop as an "attachable" function without {@attach} syntax if they're going to eventually explicitly attach it to a DOM element without spreading.

<AnotherComponent {logger}  myAction={(node) => { /* do something */ } />
<!-- AnotherComponent.svelte -->
<script>
  let { logger, myAction } = $props();
</script>

<input {@attach logger} {@attach myAction}>

@dotmrjosh
Copy link

dotmrjosh commented Jan 14, 2025

Could svelte have a set of constant symbols (assuming we're using the Symbol API)? Could also allow for updating the transition directives.

Something like:

<script>
  import { ATTACHMENT_SYMBOL, TRANSITION_IN_SYMBOL } from "svelte/symbols";
  import { fade } from "svelte/transition";

  const stuff = {
    [ATTACHMENT_SYMBOL]: (node) => console.log("hello world"),
    [TRANSITION_IN_SYMBOL]: (node) => fade(node, { duration: 100 }),
  }; 
</script>

<button {...stuff}>hello</button>

@Conduitry
Copy link
Member

The purpose of having a function that returns symbols - rather than using a single symbol - is that it lets you have multiple attachments on a single element/component without them clobbering one another.

@JonathonRP
Copy link

The current rub with transitions is their css and/or tick methods that apply to style but if transitions were just attachments that modified the style attribute of node then they would just be attachments too...

@Thiagolino8
Copy link

The current rub with transitions is their css and/or tick methods that apply to style but if transitions were just attachments that modified the style attribute of node then they would just be attachments too...

Actions can already do this already, the advantage of transitions is to do this outside the main thread
In svelte 3/4 creating css transitions and in svelte 5 using the WAAPI

@Thiagolino8
Copy link

Thiagolino8 commented Jan 14, 2025

One of the advantages of the special syntax of actions was the fact that it generated shakable tree code

Attachments do not seem to have this advantage since every element needs to look for properties with the special symbol for special behavior

@Thiagolino8
Copy link

If I understand correctly, it is not possible to extract an attachment from the props and consequently it is also not possible to prevent an attachment from being passed to an element with spread props, using an attachment on a component is basically a redirect all

@JonathonRP
Copy link

The current rub with transitions is their css and/or tick methods that apply to style but if transitions were just attachments that modified the style attribute of node then they would just be attachments too...

Actions can already do this already, the advantage of transitions is to do this outside the main thread
In svelte 3/4 creating css transitions and in svelte 5 using the WAAPI

True, I'm curious about the waapi usage

@dotmrjosh
Copy link

The purpose of having a function that returns symbols - rather than using a single symbol - is that it lets you have multiple attachments on a single element/component without them clobbering one another.

I'd be curious about the intention of this, cause intuitively I would assume using the function would override any previous definitions the same way standard merging of objects would. Allowing multiple of what at face value feels like the same key feels like it'll trip people up.
I think if you wanted to have multiple attachments through props, using a sequence function would be a lot clearer and guarantee what order attachments occur in.

<script>
  import { ATTACHMENT_SYMBOL } from "svelte/symbols";
  import { sequence } from "svelte/attachments";

  const attachmentA = (node) => console.log("first attachment");
  const attachmentA = (node) => console.log("second attachment");

  const stuff = {
    [ATTACHMENT_SYMBOL]: sequence(attachmentA, attachmentB),
  }; 
</script>

<button {...stuff}>hello</button>

@Rich-Harris
Copy link
Member Author

@huntabyte

Would something like this work as well?

try it and see :)

I wonder if it would be more flexible for composition if the syntax can work with named props.

You're just describing normal props! The {@attach ...} keyword is only useful when it's anonymous.

<MyComponent {@attach anonymousAttachment} named={namedAttachment} />
<script>
  let { named, ...props } = $props();
</script>

<div {@attach named} {...props} />

One of the advantages of the special syntax of actions was the fact that it generated shakable tree code

I don't follow? The only treeshaking that happens, happens in SSR mode — i.e. <div use:foo> doesn't result in foo being called on the server. That remains true for attachments. The additional runtime code required to support attachments is negligible.

If I understand correctly, it is not possible to extract an attachment from the props

It's deliberate that if you use {...stuff} that attachments will be included in that. If you really want to remove them it's perfectly possible, it's just an object with symbols. Create a derived that filters the symbols out if you need to, though I'm not sure why you'd want that.

Allowing multiple of what at face value feels like the same key feels like it'll trip people up.

Most of the time you're not interacting with the 'key', that's an advanced use case. You're just attaching stuff:

<div {attach foo()} {@attach bar()} {@attach etc()}>...</div>

One possibility for making that more concise is to allow a sequence...

<div {attach foo(), bar(), etc()}>...</div>

...but I don't know if that's a good idea.

@kran6a
Copy link

kran6a commented Jan 14, 2025

Love the proposal and how it simplified actions, specially the handler having a single parameter, which will not only encourage but force writing more composable attachments via HOFs.
i.e:

export const debounce = (cb: ()=>void)=>(ms: number)=>(element: HTMLElement)=>{
    // implementation intentionally left blank
}
<script lang="ts">
    const debounced_alert = debounce(()=>alert("You type too slow"));
</script>
<textarea {@attach debounced_alert(2000)}></textarea>

Personally I would prefer a block syntax rather than the PR one.

<!--Applies both attachments to input and textarea-->
{#attachment debounce(()=>alert("You type too slow"))(2000), debounce(()=>alert("Server is still waiting for input"))(3000)}
    <input type="text"/>
    <textarea></textarea>
{/attachment}

My reasons to prefer a block are:

  1. It is an already known syntax
  2. Easily discoverable via intellisense when you type {# (to write any other block) and the autocomplete brings up attachment as one of the options. I don't think anybody that does not know about attachments is going to discover the PR syntax via intellisense.
  3. Blocks are easier to read when the block content is a big tree since you can see the opening and closing. This is useful when the element that has the attachment is not an input/button but a clickoutside or a keydown on a whole page section.
  4. Syntax is cleaner even if you inline the attachment configuration options as otherwise they would be on the same line as 20 tailwind classes, an id, name, data- and aria- attributes.
  5. The {@something} syntax already exists and, until now, it could only be used inside an element/block, be it declaring a block-scoped constant with {@const}, rawdogging html with {@html}, or rendering with {@render}.
    Even debugging with {@debug} cannot be used in the opening tag like {@attachment}. This breaks sytax consistency and did not happen with the old use: syntax as the old something: syntax was always used on the opening tag of an element.

@Ocean-OS
Copy link
Contributor

I like this, my only concern is the similarity in syntax between this and logic tags. It may make new developers think that something like this is valid Svelte:

<div {@const ...}>

Or may make them try to do something like this:

<element>
{@attach ...}
</element>

@itsmikesharescode
Copy link

I love it!

@Theo-Steiner
Copy link
Contributor

Theo-Steiner commented Jan 14, 2025

Great iteration on actions, I love it!

Came here to ask how I could determine if an object property was an attachment, but looking at the source, it looks like isAttachmentKey is a helper to do just that!

Two things in particular are needed: a way to add per-element lifecycle functions, and an API for delaying the destruction of an effect until some work is complete (which outro transitions uniquely have the power to do today). This PR adds the first; the second is a consideration for our future selves.

I think it would be really intuitive if attachments could return an async cleanup function with the element/component being removed once the cleanup function (and all nested cleanup functions) settle/resolve!

dummdidumm added a commit to sveltejs/prettier-plugin-svelte that referenced this pull request May 14, 2025
dummdidumm added a commit to sveltejs/language-tools that referenced this pull request May 14, 2025
@Rich-Harris Rich-Harris merged commit b93a617 into main May 14, 2025
13 checks passed
@Rich-Harris Rich-Harris deleted the attachments branch May 14, 2025 17:33
@github-actions github-actions bot mentioned this pull request May 14, 2025
@mattpilott
Copy link
Contributor

Is it worth having a migrator for this? Will actions be deprecated?

@Ocean-OS
Copy link
Contributor

I don't think actions will be deprecated in the immediate future, but, like class:, it'll probably be deprecated at some point. Also, since there is a difference in how actions' and attachments' arguments work, it seems unlikely that a migrator tool could automate the process.

@mattpilott
Copy link
Contributor

Yes thats a good point, I wonder if there is a benefit to the built-in use:enhance action moving to a built-in attachment

@brunnerh
Copy link
Member

brunnerh commented May 14, 2025

That would enable forwarding it through form wrapper components.

@Azarattum
Copy link
Contributor

Does this PR allow attaching transitions with attachments?

@Rich-Harris
Copy link
Member Author

No. That would require an API for preventing effects from being destroyed; that hasn't been designed yet and will come later. After that, we can design a new transition API that builds on top of it and provides more flexibility than the current one.

@RyanYANG52
Copy link

Hi, @Rich-Harris . If I understand correctly, currently attachment is running inside an effect.

export function attach(node, get_fn) {
effect(() => {
const fn = get_fn();
// we use `&&` rather than `?.` so that things like
// `{@attach DEV && something_dev_only()}` work
return fn && fn(node);
});
}

I think this is very important to mention in the DOC , because it's diff from event handler and action (action untrack)

current it only says

Since the tooltip(content) expression runs inside an effect, the attachment will be destroyed and recreated whenever content changes.

I think it's unclear about what happens if state change inside attachment (return value of tooltip(content))

Another part is Inline-attachments example, if attachment already inside an effect, why create another $effect

I am not sure attachment function run inside an effect is by design.

Best regards

@MotionlessTrain
Copy link
Contributor

I think it's unclear about what happens if state change inside attachment (return value of tooltip(content))

That is exactly what happens in the example (the content state is read inside of the attachment effect, and that is what makes it recreate itself

The nested effect makes sure that it doesn’t recreate itself, but update parts of it (another example I saw was something like tippy.setContent inside of an effect, to not recreate the tooltip)

@RyanYANG52
Copy link

nested effect part I understand now, thanks. didn't find the doc about it before.

All I am saying is that maybe the doc counld be more clear about attachment is running inside an effect (not only factory part), currently only this

Attachments are functions that run when an element is mounted to the DOM. Optionally, they can return a function that is called when the element is later removed from the DOM.

I can do something like this, it still works.

sometime state is shared from outside, we need be aware of that, so we can untrack or create nested effect to avoid unwanted rerun

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.