Skip to content

fix: make immutable option work more correctly #13526

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 1 commit into from
Oct 9, 2024
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/giant-ladybugs-thank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: make immutable option work more correctly
4 changes: 2 additions & 2 deletions packages/svelte/src/compiler/phases/2-analyze/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,15 +521,15 @@ export function analyze_component(root, source, options) {

if (root.options) {
for (const attribute of root.options.attributes) {
if (attribute.name === 'accessors') {
if (attribute.name === 'accessors' && analysis.runes) {
w.options_deprecated_accessors(attribute);
}

if (attribute.name === 'customElement' && !options.customElement) {
w.options_missing_custom_element(attribute);
}

if (attribute.name === 'immutable') {
if (attribute.name === 'immutable' && analysis.runes) {
w.options_deprecated_immutable(attribute);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,9 @@ export function client_component(analysis, options) {

for (const [name, binding] of analysis.instance.scope.declarations) {
if (binding.kind === 'legacy_reactive') {
legacy_reactive_declarations.push(b.const(name, b.call('$.mutable_state')));
legacy_reactive_declarations.push(
b.const(name, b.call('$.mutable_state', undefined, analysis.immutable ? b.true : undefined))
);
}
if (binding.kind === 'store_sub') {
if (store_setup.length === 0) {
Expand Down Expand Up @@ -368,7 +370,9 @@ export function client_component(analysis, options) {
...group_binding_declarations,
...analysis.top_level_snippets,
.../** @type {ESTree.Statement[]} */ (instance.body),
analysis.runes || !analysis.needs_context ? b.empty : b.stmt(b.call('$.init')),
analysis.runes || !analysis.needs_context
? b.empty
: b.stmt(b.call('$.init', analysis.immutable ? b.true : undefined)),
.../** @type {ESTree.Statement[]} */ (template.body)
]);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/** @import { CallExpression, Expression, Identifier, Literal, VariableDeclaration, VariableDeclarator } from 'estree' */
/** @import { Binding } from '#compiler' */
/** @import { ComponentContext } from '../types' */
/** @import { Scope } from '../../../scope' */
/** @import { ComponentClientTransformState, ComponentContext } from '../types' */
import { dev } from '../../../../state.js';
import { extract_paths } from '../../../../utils/ast.js';
import * as b from '../../../../utils/builders.js';
Expand Down Expand Up @@ -267,7 +266,7 @@ export function VariableDeclaration(node, context) {
declarations.push(
...create_state_declarators(
declarator,
context.state.scope,
context.state,
/** @type {Expression} */ (declarator.init && context.visit(declarator.init))
)
);
Expand All @@ -287,12 +286,17 @@ export function VariableDeclaration(node, context) {
/**
* Creates the output for a state declaration in legacy mode.
* @param {VariableDeclarator} declarator
* @param {Scope} scope
* @param {ComponentClientTransformState} scope
* @param {Expression} value
*/
function create_state_declarators(declarator, scope, value) {
function create_state_declarators(declarator, { scope, analysis }, value) {
if (declarator.id.type === 'Identifier') {
return [b.declarator(declarator.id, b.call('$.mutable_state', value))];
return [
b.declarator(
declarator.id,
b.call('$.mutable_state', value, analysis.immutable ? b.true : undefined)
)
];
}

const tmp = scope.generate('tmp');
Expand All @@ -304,7 +308,9 @@ function create_state_declarators(declarator, scope, value) {
const binding = scope.get(/** @type {Identifier} */ (path.node).name);
return b.declarator(
path.node,
binding?.kind === 'state' ? b.call('$.mutable_state', value) : value
binding?.kind === 'state'
? b.call('$.mutable_state', value, analysis.immutable ? b.true : undefined)
: value
);
})
];
Expand Down
36 changes: 31 additions & 5 deletions packages/svelte/src/internal/client/dom/legacy/lifecycle.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,46 @@
/** @import { ComponentContextLegacy } from '#client' */
import { run, run_all } from '../../../shared/utils.js';
import { derived } from '../../reactivity/deriveds.js';
import { user_pre_effect, user_effect } from '../../reactivity/effects.js';
import { component_context, deep_read_state, get, untrack } from '../../runtime.js';

/**
* Legacy-mode only: Call `onMount` callbacks and set up `beforeUpdate`/`afterUpdate` effects
* @param {boolean} [immutable]
*/
export function init() {
export function init(immutable = false) {
const context = /** @type {ComponentContextLegacy} */ (component_context);

const callbacks = context.l.u;
if (!callbacks) return;

let props = () => deep_read_state(context.s);

if (immutable) {
let version = 0;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be a source?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it's used in the derived, and the derived then does equality checks to see whether or not the version has changed. If we had the possibility of accessing the current/previous value within the derived I would do that instead.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oooooh gotcha...thanks for the explanation

let prev = /** @type {Record<string, any>} */ ({});

// In legacy immutable mode, before/afterUpdate only fire if the object identity of a prop changes
const d = derived(() => {
let changed = false;
const props = context.s;
for (const key in props) {
if (props[key] !== prev[key]) {
prev[key] = props[key];
changed = true;
}
}
if (changed) version++;
return version;
});

props = () => get(d);
}

// beforeUpdate
if (callbacks.b.length) {
user_pre_effect(() => {
observe_all(context);
observe_all(context, props);
run_all(callbacks.b);
});
}
Expand All @@ -35,7 +60,7 @@ export function init() {
// afterUpdate
if (callbacks.a.length) {
user_effect(() => {
observe_all(context);
observe_all(context, props);
run_all(callbacks.a);
});
}
Expand All @@ -45,11 +70,12 @@ export function init() {
* Invoke the getter of all signals associated with a component
* so they can be registered to the effect this function is called in.
* @param {ComponentContextLegacy} context
* @param {(() => void)} props
*/
function observe_all(context) {
function observe_all(context, props) {
if (context.l.s) {
for (const signal of context.l.s) get(signal);
}

deep_read_state(context.s);
props();
}
12 changes: 8 additions & 4 deletions packages/svelte/src/internal/client/reactivity/sources.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,15 @@ export function state(v) {
/**
* @template V
* @param {V} initial_value
* @param {boolean} [immutable]
* @returns {Source<V>}
*/
/*#__NO_SIDE_EFFECTS__*/
export function mutable_source(initial_value) {
export function mutable_source(initial_value, immutable = false) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than doing this, can't we just use the non-mutable source instead?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, because this method additionally adds the source to the before/afterUpdate array, which is necessary in legacy mode

const s = source(initial_value);
s.equals = safe_equals;
if (!immutable) {
s.equals = safe_equals;
}

// bind the signal to the component context, in case we need to
// track updates to trigger beforeUpdate/afterUpdate callbacks
Expand All @@ -86,10 +89,11 @@ export function mutable_source(initial_value) {
/**
* @template V
* @param {V} v
* @param {boolean} [immutable]
* @returns {Source<V>}
*/
export function mutable_state(v) {
return push_derived_source(mutable_source(v));
export function mutable_state(v, immutable = false) {
return push_derived_source(mutable_source(v, immutable));
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<svelte:options immutable />

<script>
import { afterUpdate, beforeUpdate } from 'svelte';

export let todo;

let btn;

$: console.log('$:'+ todo.id);

beforeUpdate(() => {
console.log('beforeUpdate:'+ todo.id);
})

afterUpdate(() => {
console.log('afterUpdate:'+ todo.id);
});
</script>

<button bind:this={btn} on:click>
{todo.done ? 'X' : ''}
{todo.id}
</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
immutable: true,

html: '<button>1</button> <button>2</button> <button>3</button>',

test({ assert, target, logs }) {
assert.deepEqual(logs, [
'$:1',
'beforeUpdate:1',
'$:2',
'beforeUpdate:2',
'$:3',
'beforeUpdate:3',
'afterUpdate:1',
'afterUpdate:2',
'afterUpdate:3',
'beforeUpdate:1',
'beforeUpdate:2',
'beforeUpdate:3'
]);

const [button1, button2] = target.querySelectorAll('button');

logs.length = 0;
button1.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
'<button>X 1</button> <button>2</button> <button>3</button>'
);
assert.deepEqual(logs, ['$:1', 'beforeUpdate:1', 'afterUpdate:1']);

logs.length = 0;
button2.click();
flushSync();
assert.htmlEqual(
target.innerHTML,
'<button>X 1</button> <button>X 2</button> <button>3</button>'
);
assert.deepEqual(logs, ['$:2', 'beforeUpdate:2', 'afterUpdate:2']);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<script>
import ImmutableTodo from './ImmutableTodo.svelte';

let todos = [
{ id: 1, done: false },
{ id: 2, done: false },
{ id: 3, done: false }
];

function toggle(id) {
todos = todos.map((todo) => {
if (todo.id === id) {
return {
id,
done: !todo.done
};
}

return todo;
});
}
</script>

{#each todos as todo}
<ImmutableTodo {todo} on:click={() => toggle(todo.id)} />
{/each}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { flushSync } from 'svelte';
import { test } from '../../test';

export default test({
immutable: true,

html: '<button>0</button> <button>0</button>',

test({ assert, target }) {
const [button1, button2] = target.querySelectorAll('button');

button1.click();
flushSync();
assert.htmlEqual(target.innerHTML, '<button>0</button> <button>0</button>');

button2.click();
flushSync();
assert.htmlEqual(target.innerHTML, '<button>2</button> <button>2</button>');
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
let name = { value: 0 };
</script>

<button onclick={() => name.value++}>{name.value}</button>
<button onclick={() => (name = { value: name.value + 1 })}>{name.value}</button>