Non-updated state treated differently in different places
#14280This further improves the partial evaluation implemented in #15494. It accounts for sources that are declared as $state, but never reassigned to (and can be treated as constants), and other (somewhat more complex) cases.
A few possible end goals for this:
function get_pi() {
return 3.14159265358979; //constant value
}
String(stuff); //string type
Math.random(); //number
closes #14280
feat:, fix:, chore:, or docs:.packages/svelte/src, add a changeset (npx changeset).pnpm test and lint the project with pnpm lintMinor, but given a component like this...
<script>
let a = $state(1);
let b = $state(2);
</script>
<p>{a} + {b} = {a + b}</p>
...neither a nor b is turned into state, because they are never updated. But the contents of the <p> are put in an effect anyway:
export default function App($$anchor) {
let a = 1;
let b = 2;
var p = root();
var text = $.child(p);
p.textContent = `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`;
$.reset(p);
$.template_effect(() => $.set_text(text, `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`));
$.append($$anchor, p);
}
Whatever logic is used for determining whether it's a = 1 or a = $.state(1) should also be used for determining whether to create an effect.
No response
next
annoyance
Similarly, I think it'd be useful if we determined when any state updates happen to see if we really need to make a value a $.state. For example, in this code, a doesn't necessarily need to become a $.state.
If we could, (I'm not sure how doable this is), we could just figure out the updated value of a state and assign it at the declaration. Example:
let a = $state(1);
a++;
//becomes
let a = 2; //assuming `a` doesn't update anywhere elseexport default function App($$anchor) { let a = 1; let b = 2; var p = root(); var text = $.child(p); p.textContent = `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`; $.reset(p); $.template_effect(() => $.set_text(text, `${a ?? ""} + ${b ?? ""} = ${a + b ?? ""}`)); $.append($$anchor, p); }
Out of curiosity, is there a reason you chose to use p.textContent instead of $.set_text?