fix: ensure computed props are wrapped in derived (#9835)

pull/9841/head
Dominic Gannaway 12 months ago committed by GitHub
parent d9c250a4bf
commit e2dcdc2887
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: ensure computed props are wrapped in derived

@ -782,13 +782,20 @@ function serialize_inline_component(node, component_name, context) {
if (attribute.metadata.dynamic) {
let arg = value;
const contains_call_expression =
// When we have a non-simple computation, anything other than an Identifier or Member expression,
// then there's a good chance it needs to be memoized to avoid over-firing when read within the
// child component.
const should_wrap_in_derived =
Array.isArray(attribute.value) &&
attribute.value.some((n) => {
return n.type === 'ExpressionTag' && n.metadata.contains_call_expression;
return (
n.type === 'ExpressionTag' &&
n.expression.type !== 'Identifier' &&
n.expression.type !== 'MemberExpression'
);
});
if (contains_call_expression) {
if (should_wrap_in_derived) {
const id = b.id(context.state.scope.generate(attribute.name));
context.state.init.push(b.var(id, b.call('$.derived', b.thunk(value))));
arg = b.call('$.get', id);

@ -0,0 +1,10 @@
<script>
import { log } from './log.js';
const {active} = $props();
$effect.pre(() => {
log.push('active changed', active)
});
</script>
<p>Item is {active ? 'active' : 'inactive'}</p>

@ -0,0 +1,19 @@
import { test } from '../../test';
import { flushSync } from 'svelte';
import { log } from './log.js';
export default test({
before_test() {
log.length = 0;
},
async test({ assert, target }) {
log.length = 0;
const input = /** @type {HTMLInputElement} */ (target.querySelector('input'));
input.value = '1';
flushSync(() => input.dispatchEvent(new window.Event('input')));
assert.deepEqual(log, ['active changed', false, 'active changed', true]);
}
});

@ -0,0 +1,2 @@
/** @type {any[]} */
export const log = [];

@ -0,0 +1,11 @@
<script>
import Item from './Item.svelte';
let activeIndex = $state(0);
</script>
<input bind:value={activeIndex} type="number" min="0" max={4} />
<Item active={activeIndex == 0} />
<Item active={activeIndex == 1} />
<Item active={activeIndex == 2} />
<Item active={activeIndex == 3} />
<Item active={activeIndex == 4} />
Loading…
Cancel
Save