-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
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
feat: attachments #15000
Conversation
🦋 Changeset detectedLatest commit: 8255bc6 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! |
Is it worth having a migrator for this? Will actions be deprecated? |
I don't think actions will be deprecated in the immediate future, but, like |
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 |
That would enable forwarding it through form wrapper components. |
Does this PR allow attaching transitions with attachments? |
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. |
Hi, @Rich-Harris . If I understand correctly, currently
I think this is very important to mention in the DOC , because it's diff from current it only says
I think it's unclear about what happens if state change inside attachment (return value of Another part is Inline-attachments example, if attachment already inside an effect, why create another I am not sure attachment function run inside an effect is by design. Best regards |
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) |
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
I can do something like this, it still works. sometime state is shared from outside, we need be aware of that, so we can |
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