Skip to content

fix: only re-run directly applied attachment if it changed #15962

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 5 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/slimy-drinks-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: only re-run directly applied attachment if it changed
30 changes: 24 additions & 6 deletions packages/svelte/src/internal/client/dom/elements/attachments.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
import { effect } from '../../reactivity/effects.js';
/** @import { Effect } from '#client' */
import { block, branch, effect, destroy_effect } from '../../reactivity/effects.js';

// TODO in 6.0 or 7.0, when we remove legacy mode, we can simplify this by
// getting rid of the block/branch stuff and just letting the effect rip.
// see https://github.com/sveltejs/svelte/pull/15962

/**
* @param {Element} node
* @param {() => (node: Element) => void} get_fn
*/
export function attach(node, get_fn) {
effect(() => {
const fn = get_fn();
/** @type {false | undefined | ((node: Element) => void)} */
var fn = undefined;

/** @type {Effect | null} */
var e;

block(() => {
if (fn !== (fn = get_fn())) {
if (e) {
destroy_effect(e);
e = null;
}

// we use `&&` rather than `?.` so that things like
// `{@attach DEV && something_dev_only()}` work
return fn && fn(node);
if (fn) {
e = branch(() => {
effect(() => /** @type {(node: Element) => void} */ (fn)(node));
});
}
}
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
test({ assert, target, logs }) {
assert.deepEqual(logs, ['up']);

const button = target.querySelector('button');

flushSync(() => button?.click());
assert.deepEqual(logs, ['up']);

flushSync(() => button?.click());
assert.deepEqual(logs, ['up', 'down']);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<script>
let state = {
count: 0,
attachment(){
console.log('up');
return () => console.log('down');
}
};
</script>

<button onclick={() => state.count++}>{state.count}</button>

{#if state.count < 2}
<div {@attach state.attachment}></div>
{/if}