-
-
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! |
on is not a prefix, its just exposing the actual HTML event name as it is! Whereas attach is an arbitrary prefix out of nowhere which would break Types, require a major, as well as harder to explain and too hard to spot in the wild. |
It would not brake types any harder than custom events? Also 'on' IS a prefix although not created by svelte. |
@huntabyte As a point of order, your 'named' code wouldn't actually work — you need to jump through some extra hoops: +import { createAttachment } from 'svelte/attachments';
// named
-const namedBaseAttachments = { hover: node => {}, focus: node => {} }
-const namedDragAttachments = { drag: node => {}, dropzone: node => {} }
-const namedTooltipAttachments = { tooltip: node => {}, aria: node => {} }
+const namedBaseAttachments = { hover: createAttachment(node => {}), focus: createAttachment(node => {}) }
+const namedDragAttachments = { drag: createAttachment(node => {}), dropzone: createAttachment(node => {}) }
+const namedTooltipAttachments = { tooltip: createAttachment(node => {}), aria: createAttachment(node => {}) } But leaving that aside, let's interrogate this in more detail: there are basically two possibilities, one in which <button {...props}>{@render children?.()}</button> In this case there's no advantage to the consumer to using named attachments — the name is an opportunity for accidental clobbering, nothing more. In the other case, <button {@attach hover} {@attach drag} {@attach tooltip} {...props}>{@render children?.()}</button> ...which seems onerous. But look closer: it makes no sense to do this. If my <script>
import { on } from 'svelte/events';
let { children, hover, drag, tooltip, ...props } = $props();
</script>
<button
{...props}
{@attach hover && (node) => {
on(node, 'mouseenter', () => {
const cleanup = hover();
on(node, 'mouseleave', cleanup);
});
}}
{@attach tooltip && (node) => {
const { destroy } = tippy(node, { content: tooltip });
return destroy;
}}
> ...and you'd use it like this: <Button
class="cool-button"
onclick={() => console.log('clicked')}
tooltip="wheee!!!!"
{@attach fade.in()}
> To reiterate the point about clobbering: a function that creates a bunch of attachments (or attachments and props) for use on arbitrary elements can't just claim random names for itself. Even if it studiously avoids any attribute that exists in HTML today, it can't guarantee attributes won't be added in future, and it can't guarantee those attributes/properties aren't in use by custom elements. What am I missing here? |
I think the main point of @huntabyte is not for users of components but users of functions. Libraries like melt provide actions to use on elements, not components. And his point is that as a library maintainer and user is much better to have named attachments. But at the same time you might want to exclude some attachment because you don't need them. So if you have something like this <script>
let { drag, ...other_20_attachments } = get_attachments();
</script>
<div {...other_20_attachments} /> You currently have no way of doing it. I think this could be solved by this tho <script>
let { drag, ...other_20_attachments } = get_attachments();
</script>
<div {@attach ...other_20_attachments} /> |
This problem is a similar to bindings which you also can't spread today, and some people requested |
I'm not sure I understand this point as it pertains to attachments. If the value of a named attachment property is an attachment (identify by Symbol), then the prop / attribute name is completely ignored and never added to the dom elements. As far as components clubbering is possible just like with any prop. Or is this about something else? |
I had an idea to possible help with having names for code base reuse of common attachment functions -import { createAttachment } from 'svelte/attachments';
// named
-const namedBaseAttachments = { hover: node => {}, focus: node => {} }
-const namedDragAttachments = { drag: node => {}, dropzone: node => {} }
-const namedTooltipAttachments = { tooltip: node => {}, aria: node => {} }
-const namedBaseAttachments = { hover: createAttachment(node => {},) focus: createAttachment(node => {}) }
-const namedDragAttachments = { drag: createAttachment(node => {},) dropzone: createAttachment(node => {}) }
-const namedTooltipAttachments = { tooltip: createAttachment(node => {},) aria: createAttachment(node => {}) }
+const namedBaseAttachments = new Map([['hover', node => {}], ['focus', node => {}]])
+const namedDragAttachments = new Map([['drag', node => {}], ['dropzone': node => {}]])
+const namedTooltipAttachments = new Map([['tooltip', node => {}], ['aria', node => {}]]) @huntabyte, I know this is a little harder to read, maybe not so clear as Object but it would allow for more performant access and no need to have createAttachment or changes to current PR. do you think this is a solutions or did I misunderstand your concerns? usage - <div {@attach namedBaseAttachments.get('hover')} {@attach namedBaseAttachments.get('focus')} /> |
This is already possible with object destructuring...what he wants is be able to spread every except the destructured ones. |
This is dangerous... import { createAttachment } from 'svelte';
export function createCoolAttachments() {
return {
tom: createAttachment((node) => {...}),
dick: createAttachment((node) => {...}),
harry: createAttachment((node) => {...})
};
} <script>
import { createCoolAttachments } from 'some-library';
</script>
<my-element {...createCoolAttachments()}>...</my-element> ...because |
However i just realised there's actually a way to do it (maybe not as nice as destructuring). You can have this import { on } from "svelte/events";
type Attachment = (node: HTMLElement) => unknown;
const attachments = {
log(node) {
console.log(node);
},
alert(node) {
$effect(() => {
return on(node, "click", () => {
alert("clicked");
})
})
},
log_click(node) {
$effect(() => {
return on(node, "click", () => {
alert("clicked");
})
})
},
} as const satisfies Record<string, Attachment>;
export function get_attachments(wanted: Array<keyof typeof attachments>) {
const unique_want = new Set(wanted);
const ret: Record<symbol, Attachment> = {};
for (const want of unique_want) {
ret[Symbol()] = attachments[want];
}
return ret;
} and this would allow you to have autocompletion on the available attachments and be able to selectively spread every attachment on elements too. |
but we are in the svelte codebase and this still goes through compilation, right? |
Excited to see this one get in 🥳 Some really nice additional power on top of actions, which are already pretty great as-is 😅 I do think I agree with some of the sentiment here that a greater separation of concerns between props and attachments might be a bit more intuitive/predictable in this case, rather than needing this additional concept of attachment keys/symbols that automatically get attached if they happen to be spread as props. I was able to reason about the new I think in practice the solution to this would simply mean leaning into the <button {...props} {@attach ...attachments} /> An additional complexity to this I can think of, though, is for the component attachments use case. To have this stronger separation of props and attachments (i.e., attachments shouldn't be returned by <script>
const attachments = $attachments();
</script>
<button {@attach ...attachments} /> Not super confident on what that syntax should be though. |
What about <script>
const attachments = $props({attachmentsOnly: true})
const props = $props()
const props_without_attachments = $props({attachments: false})
</script> Would work with events too. |
I think the attachments as props and spreading is fine, I think others are discussing how to handle the programmatic creation of attachment functions and desiring to have string key names that handle the attaching rather than Symbol key to have reusable and composable attachment functions in repos/libs |
Attachments are not supposed to be distinct from props. That's the whole point — they're supposed to be something that an element wrapper component ( There's no argument for separating attachments from props that couldn't apply just as well to event handlers or snippets (or insert-other-thing-you-can-make-a-case-for-being-ontologically-distinct). And indeed people made arguments for all sorts of things like |
@Leonidaz, I think he means imagine if html gets new props in an update that allow new functionality whose name could also happen to be 'tom', 'dick' and 'harry' not that the names wouldn't be compiled out... |
Yes this was pretty much solved here I was reacting on
I agree with this choice but is there really need for having a choice to make after all? What's the downside of adding parameters to
I don't see where would the mistake be today with |
Basically, if svelte removes the passed in prop names and just attaches the attachments, but later the custom element ends up adding new attributes with these names? Svelte still never passes in these props as they're attachments. If new ones are added to custom element this would result in nothing being passed in for these attributes, it's the same as for regular dom. But if these new attributes are now required then the person calling the custom element needs to adjust their code. This would be the case with any code. Basically, named attachments are anonymous for dom or custom elements. They're not attributes. The names are only useable by components. Maybe I'm misunderstanding something? |
Aside from the fact that it's a bit of an ugly signature (I strongly dislike functions that return a different category of thing based on some parameter — it's usually emblematic of a flawed design), how would it even work? Do we assume that every component prop beginning with <Mirepoix carrot={5} celery={3} onion={7} /> Oops, that doesn't work — <script>
let { interactive } = $props();
</script>
<Canvas onmousemove={interactive ? (e) => {...} : undefined} />
The same applies to snippets and attachments, both of which can be set later, after the props have been defined. |
I read through the responses and I still think that named attachments have a lot of value in terms of usage and readability. It would be great to have a choice to use one or the other as needed. Usability:
Readability (even if the component doesn't expect named params):
The
Transitions:
|
Once again: this makes absolutely no sense. You simply would not expose a |
are we not able to do, <Button tooltip={@attach (node) => {}}/> |
No. You can do this if <Button tooltip={(node) => {...}}> ...or this if it doesn't: <Button {@attach (node) => {...}}> |
@Rich-Harris, oh! gotcha, thanks! |
The first example was just to start a conversation about having to use regular function vs an attachment when it's not needed. It goes on further to "distributing" props for multiple elements / nested components.
And, just to clarify, I completely agree with you that frequently a component just needs a callback prop and it will handle the attachment via wrapper. But it's not always the case. There were also other points in my last comment about readability and syntax. |
I have been waiting for something like this for some time in order to use it with |
I was mentally thinking the following about Svelte syntax {------ expression ------}
decorator | expression
{@render snippet()}
{@html source}
{@debug variable} Then came {---------- declation ----------}
keyword | id | expression
no decorator
{@const res = whatever()} Now the syntax of {-- expression/attr/declaration --}
attr?/decorator | expression
{@attach ()=>{}|fn()|id} We remember some things that are no longer there with affection but ultimately were/are obstacles to moving forward. I imagine it more consistent (the symbol // psudo attrs
// future (with mechanisms for spreading)
@attach={}
@transition={}
@in={}
@out={}
@animate={}
@bind={} ?? // """pseudo"""@decorator
{@render snippet()}
{@html source}
{@debug variable} // control
{#const t = foo()}
{#snippet child()}
{#if cond}
{#each user as user}
{#await promise} |
I think there's a need here to confirm the desired behaviour and limitations of component attachments. When you apply an attachment to a regular element, it's predictable that it will be attached directly to that element. However, treating attachments as props for the component case muddies this, as they could end up attached to any and all elements that exist inside the component. It seems like for predictability, component attachments should only be able to be applied to a single element inside a component, but the current implementation doesn’t really have a way to enforce this.
The introduction of the But also to completely backtrack on my previous suggestion of only being able to attach using the For defining attachments inline, this could look something like what others have suggested above with the <Button @attach={(node) => doSomething()} /> // `@attach` is a reserved prop keyword, which creates a new AttachSymbol() as the attachment prop key when used This is probably the cleanest syntax for adding attachments directly on an element or component, and it also makes it somewhat clearer to associate an attachment as a prop. That said, this does feel like a somewhat dubious improvement on More in line with the idea of having only one way of doing something, perhaps then prop keys could instead be expanded to support computed property names, allowing the attach symbol to be created directly as the key to define an attachment instead. i.e.: <Button [AttachSymbol()]={(node) => doSomething()} /> This is something you can already achieve with the current implementation when spreading props onto an object. e.g. <Button {...{[AttachSymbol()]: (node) => doSomething()}} /> so it raises the question why it shouldn't also be achievable to do this directly on the prop key as well. Separately but related, I’m not sure what the main motivator was for switching to Presumably, it was just for the global availability of Perhaps the global availability benefit could still be achieved by having something like Whatever the method for creating attachment keys might look like aside, the current implementation feels like a one-way door—if there ever is a need or desire for symbols to be used as property keys for non-attachment purposes, the current behaviour would make that change extremely difficult, if not impossible. |
There's still a lot of people seemingly not convinced of the current implementation, and I wonder if you guys have test-driven the current implemenation. I have: POC for floating-ui After writing it, I don't think I have a single complaint.
Furthermore, my expectations:
ConclusionI'm satisfied, I think, as a consumer and as a library creator. Right now, I cannot think of a single extra thing that I want. |
|
||
let stuff = $state({ | ||
[Symbol()]: (node) => node.textContent = 'set from component' | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
test should be enhanced to test that when removing the old symbol and adding a new one that the old one is cleaned up properly
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