Skip to content

Commit 8ba0012

Browse files
committed
feat: single line labeled statement state
1 parent c7d6d32 commit 8ba0012

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

packages/svelte/src/compiler/migrate/index.js

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,9 @@ const instance_script = {
610610
node.body.expression.type === 'AssignmentExpression'
611611
) {
612612
const ids = extract_identifiers(node.body.expression.left);
613+
const [, expression_ids] = extract_all_identifiers_from_expression(
614+
node.body.expression.right
615+
);
613616
const bindings = ids.map((id) => state.scope.get(id.name));
614617
const reassigned_bindings = bindings.filter((b) => b?.reassigned);
615618
if (reassigned_bindings.length === 0 && !bindings.some((b) => b?.kind === 'store_sub')) {
@@ -640,14 +643,24 @@ const instance_script = {
640643
return;
641644
} else {
642645
for (const binding of reassigned_bindings) {
643-
if (binding && ids.includes(binding.node)) {
646+
if (binding && (ids.includes(binding.node) || expression_ids.length === 0)) {
647+
const init =
648+
binding.kind === 'state'
649+
? ' = $state()'
650+
: expression_ids.length === 0
651+
? ` = $state(${state.str.original.substring(/** @type {number} */ (node.body.expression.right.start), node.body.expression.right.end)})`
652+
: '';
644653
// implicitly-declared variable which we need to make explicit
645-
state.str.prependRight(
654+
state.str.prependLeft(
646655
/** @type {number} */ (node.start),
647-
`let ${binding.node.name}${binding.kind === 'state' ? ' = $state()' : ''};\n${state.indent}`
656+
`let ${binding.node.name}${init};\n${state.indent}`
648657
);
649658
}
650659
}
660+
if (expression_ids.length === 0 && !bindings.some((b) => b?.kind === 'store_sub')) {
661+
state.str.remove(/** @type {number} */ (node.start), /** @type {number} */ (node.end));
662+
return;
663+
}
651664
}
652665
}
653666

packages/svelte/tests/migrate/samples/single-assignment-labeled/input.svelte

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,12 @@
4646
4747
let should_be_state;
4848
$: should_be_state = 42;
49+
$: should_be_state_too = 42;
4950
</script>
5051

5152
<button on:click={()=>{
5253
count++;
5354
eight_times++;
5455
sixteen_times += 1;
56+
should_be_state_too++;
5557
}}>click</button>

packages/svelte/tests/migrate/samples/single-assignment-labeled/output.svelte

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,13 @@
4646
4747
let should_be_state = $state(42);
4848
49+
let should_be_state_too = $state(42);
50+
4951
</script>
5052

5153
<button onclick={()=>{
5254
count++;
5355
eight_times++;
5456
sixteen_times += 1;
57+
should_be_state_too++;
5558
}}>click</button>

0 commit comments

Comments
 (0)