-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
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
feat: attachments #15000
base: main
Are you sure you want to change the base?
feat: attachments #15000
Conversation
🦋 Changeset detectedLatest commit: 6402161 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
preview: https://svelte-dev-git-preview-svelte-15000-svelte.vercel.app/ this is an automated message |
|
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:
|
Personally I would prefer a createAttachment like createSnippet. Just something to consider for the team |
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 <AnotherComponent {logger} myAction={(node) => { /* do something */ } /> <!-- AnotherComponent.svelte -->
<script>
let { logger, myAction } = $props();
</script>
<input {@attach logger} {@attach myAction}> |
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> |
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. |
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 |
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 |
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 |
True, I'm curious about the waapi usage |
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. <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> |
You're just describing normal props! The <MyComponent {@attach anonymousAttachment} named={namedAttachment} /> <script>
let { named, ...props } = $props();
</script>
<div {@attach named} {...props} />
I don't follow? The only treeshaking that happens, happens in SSR mode — i.e.
It's deliberate that if you use
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. |
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. 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:
|
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> |
I love it! |
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
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! |
I agree, I think we're over thinking the usability of attachments. The only case I could think of is the ability to destructor from an object holding command reusable attachment functions and taking out some and spreading the rest, as pointed out previously. But again that could be easily added later. I think the conversation should pivot to helping discuss about transition and animation handling/ implementation if there should be continued discussions here at all. |
Now that we have runes in v5, I would get rid of this syntax and use runes instead and in general stick more to the javascript syntax. The only kind of an issue is that stores use the {$render(snippet())}
{$html(source)}
{$debug(variable)}
{const something = 'something'} Likely for So, back to attachments, transitions, animations, etc. I wouldn't even add anything special and just treat them as regular props. for anonymous props just let the compiler convert unnamed props to anonymous props import { attach } from 'svelte/attachments';
import { transition } from 'svelte/transitions';
<Component
{attach((node) => {})}
named={attach((node) => {}}
{transition((action, options) => {})}
fader={transition((action, options) => {})}
/> all unnamed props, the compiler just compiles to: const props = {[Symbol()]: attach((node) => {}), [Symbol()]: transition((action, options) => {})}; |
@Leonidaz This would be a huge and unnecessary breaking change, and will just make everything far more confusing. Where does the boundary of runes start, where does it end? What even is a rune. Right now you can define runes clearly, with this you cannot. Coming back to the point, this discussion is about attachment syntax and discussions related only to this topic, not about changing entire framework's syntax :) |
This was in context, still on the subject and in reply to another comment. This lays out my thinking about using the special And if you notice, the second half of my comment talks specifically about attachments.
I'm not sure what you mean, take a look at |
@Leonidaz I think this is a topic to be addressed at another time. For now I'll just say to look back to see how future syntax can be more consistent, learning from syntax that didn't age well. "Optimise for Vibes" is a notable strength of Svelte. The substance and the form matter too. |
@Rich-Harris after test-driving this thing, I noticed that attachments are a way to reach the |
Wdym by this? |
@dangelomedinag Again, I specifically talk about the attachment syntax in my original comment.
|
This: <Button onclick={() => shown = !shown} {@attach ref} {@attach () => () => shown = false}>
A: I have a tooltip! Click me to show it.
</Button> I wrote the second attach to hide the tooltip once the component unmounts. |
@webJose |
@JonathonRP It's in the POC for floating-ui that I linked to earlier. |
@Leonidaz is much more code to reuse the return of the first |
<Button onclick={() => shown = !shown} {@attach ref(destroy: () => shown = false)}>
A: I have a tooltip! Click me to show it.
</Button> export ref(destroy: () => void) {
return () => destroy
} @webJose this is sudo code for an idea not exactly copy/paste. but idea is make ref be a function that takes a function and runs original code but returns the function it took in for destroy logic |
But most importantly it's not the unmount of the component but the unmount of the element where the attachments are spreaded |
Ok, yes. That's true. And only if the component opts to spread it. I, as consumer of the component, have no saying in what the component actually does with the attachment. No worries here, then. 👍 |
@Rich-Harris I think I have only one more ask: Typing. export type CleanupFn = () => void; // This is used in a lot of places across Svelte, not just attachments.
export type AttachmentFn = (node: HTMLElement) => void | CleanupFn; // Or Node instead of HTMLElement? I never know. If, in the future, the shape of attachment functions change, we don't have to change our own private typings. |
It would be nice to consider the ergonomics of introducing Eg: <div {:attach (node) => console.log(node)}>...</div>
or
<div {+attach (node) => console.log(node)}>...</div> |
@khromov I think you're too late with that argument, since "@" has been long established in other parts of Svelte for years. But your message brings the possibility of a feature request? Make, as much as possible, configurable symbols. Maybe compiler options could define the "shape" of keywords? This, of course, would be unrelated to this PR. |
The thing about having configurable syntax to that extent is that it makes every Svelte app and component's source code very different and confusing. If you use someone else's component, you'd also have to use whatever syntax choices they used as well. |
You're probably right, @Ocean-OS. I was trying to be helpful. I guess it is a long shot. |
"European keyboards" are not a thing, there are dozens of different ISO layouts each with their own specificity, and each OS also has their own specific sub-layout (like the |
console.log is displayed first inside an attachment and then console.log when the component is mounted. |
This is how it works in svelte in general, the template effects run first, otherwise |
Controversial idea: DOM runes ? We do have We already have At component level, nothing change, you can just pass whatever prop you want, you name it the way you want, these are just functions in the end. 🙏 Please don't say this is not the topic, you're off topic, the syntax is |
The main idea behind this was exactly to prevent you to go to the script to do simple Dom manipulations...you can basically already do this with actions |
Normal runes are already DOM runes because their state is updated in the DOM, what you're saying can already be achieved in whatever way you want using runes. Not sure what the feature of a DOM rune would be. |
For me runes are designed for JavaScript objects. It's like Signals to notify listeners when properties change on objects. What I suggest is runes for when DOM nodes are inserted, removed and updated. Just like we could do it with a giant MutationObserver, but thanks to Svelte being a compiler we can know when these insertions/deletions occurred at build time, and associate functions provided with them. No need for the Observer. |
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:
<div use:foo={bar}>
implies some sort of equality betweenfoo
andbar
but actually meansfoo(div, bar)
. There's no way you could figure that out just by looking at itfoo
inuse:foo
has to be an identifier. You can't, for example, douse:createFoo()
— it must have been declared elsewherefoo
changes,use:foo={bar}
does not re-run. Ifbar
changes, andfoo
returned anupdate
method, that method will re-run, but otherwise (including if you use effects, which is how the docs recommend you use actions) nothing will happenWe 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 ...}
, wherefn
is a function that takes the element as its sole argument:This can of course be a named function, or a function returned from a named function...
...which I'd expect to be the conventional way to use attachments.
Attachments can be create programmatically and spread onto an object:
As such, they can be added to components:
Since attachments run inside an effect, they are fully reactive.
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
feat:
,fix:
,chore:
, ordocs:
.packages/svelte/src
, add a changeset (npx changeset
).Tests and linting
pnpm test
and lint the project withpnpm lint