Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix: optimise || expressions in template #15092

Merged
merged 1 commit into from
Jan 22, 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/large-islands-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: optimise || expressions in template
Original file line number Diff line number Diff line change
Expand Up @@ -118,22 +118,22 @@ export function build_template_chunk(
// extra work in the template_effect (instead we do the work in set_text).
return { value, has_state };
} else {
let expression = value;
// only add nullish coallescence if it hasn't been added already
if (value.type === 'LogicalExpression' && value.operator === '??') {
const { right } = value;
// `undefined` isn't a Literal (due to pre-ES5 shenanigans), so the only nullish literal is `null`
// however, you _can_ make a variable called `undefined` in a Svelte component, so we can't just treat it the same way
if (right.type !== 'Literal') {
expression = b.logical('??', value, b.literal(''));
} else if (right.value === null) {
// if they do something weird like `stuff ?? null`, replace `null` with empty string
value.right = b.literal('');
// add `?? ''` where necessary (TODO optimise more cases)
if (
value.type === 'LogicalExpression' &&
value.right.type === 'Literal' &&
(value.operator === '??' || value.operator === '||')
) {
// `foo ?? null` -=> `foo ?? ''`
// otherwise leave the expression untouched
if (value.right.value === null) {
value = { ...value, right: b.literal('') };
}
} else {
expression = b.logical('??', value, b.literal(''));
value = b.logical('??', value, b.literal(''));
}
expressions.push(expression);

expressions.push(value);
}

quasi = b.quasi('', i + 1 === values.length);
Expand Down
Loading