Skip to content

fix: evaluate dynamic image sources once - #16900

Merged
teemingc merged 13 commits into
version-3from
teemingc-avoid-duplicate-function-calls
Aug 26, 2026
Merged

fix: evaluate dynamic image sources once#16900
teemingc merged 13 commits into
version-3from
teemingc-avoid-duplicate-function-calls

Conversation

@teemingc

@teemingc teemingc commented Aug 22, 2026

Copy link
Copy Markdown
Member

Fixes: #12231

This PR tries to add a Svelte declaration tag if the image source is an expression that should only be computed once.

  • It requires a newer version of Svelte to do so, which is a a breaking change. uses the old declaration tag by wrapping it in an if block that is always true. This works in both legacy and runes mode
  • It also replaces svelte-markup-parser with the official Svelte parser so that we can check for colliding declaration references.

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.

Tests

  • Run the tests with pnpm test and lint the project with pnpm lint and pnpm check

Targeted validation: enhanced-img formatting and type checks, unit tests, integration tests, and diff checks.

Changesets

  • If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpm changeset and following the prompts. Changesets that add features should be minor and those that fix bugs should be patch. Please prefix changeset messages with feat:, fix:, or chore:.

Added a patch changeset for @sveltejs/enhanced-img.

Edits

  • Please ensure that 'Allow edits from maintainers' is checked. PRs without this option may be closed.

teemingc and others added 9 commits August 22, 2026 02:55
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@pkg-svelte-dev

pkg-svelte-dev Bot commented Aug 22, 2026

Copy link
Copy Markdown

Install the latest version of @sveltejs/kit from bbe4b52:

pnpm add https://pkg.svelte.dev/@sveltejs/kit/c/bbe4b52a72370f78763a5c88e1c5f7d39c93e840

Open in pkg.svelte.dev: https://pkg.svelte.dev/repos/kit/pr/16900

@changeset-bot

changeset-bot Bot commented Aug 22, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: bbe4b52

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@sveltejs/enhanced-img Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@svelte-docs-bot

Copy link
Copy Markdown

Comment thread packages/enhanced-img/src/vite-plugin.js
/**
* @param {Expression | Super} expression
*/
function is_reference(expression) {

@teemingc teemingc Aug 22, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Comment thread packages/enhanced-img/src/vite-plugin.js Outdated
vercel Bot and others added 2 commits August 22, 2026 10:47
…nst ...}` declaration tag, which throws a hard compile error ("Declaration tags cannot be used in legacy mode") in any legacy-mode component, and is also non-reactive in the cases where it does compile.

This commit fixes the issue reported at packages/enhanced-img/src/vite-plugin.js:419

## The bug

To avoid evaluating a computed `src` expression multiple times (once per template
position), `dynamic_img_to_picture` in `packages/enhanced-img/src/vite-plugin.js`
(line ~419) caches it in a Svelte **declaration tag**:

```js
`${src_expression ? `{const ${src_var_name} = ${src_expression}}\n` : ''}...`
```

Note the bare `{const}`, not `{@const}`. This has two problems, one of them fatal.

### 1. Hard compile error in legacy-mode components (primary failure)

Declaration tags (`{const ...}`) were only added in Svelte 5.56 and are **not
allowed in legacy-mode components** — the compiler throws:

> `Declaration tags cannot be used in legacy mode`

Verified against `svelte@5.56.10`, a component's mode determines the outcome:

| Component contents | Result with `{const}` |
| --- | --- |
| `export let` (legacy) | **THROW** |
| `$:` reactive statement (legacy) | **THROW** |
| `<svelte:options runes={false} />` | **THROW** |
| plain `let` only (ambiguous) | OK |
| runes (`$props`, `$state`) | OK |

So **any legacy-mode Svelte component** containing
`<enhanced:img src={dynamicExpression}>` will **fail to compile**. This is a
regression introduced by the "evaluate dynamic sources once" change (commit
`1d1bd60`), which also bumped the `svelte` peer dep from `^5.0.0` to `^5.56.0`.

Why the existing test suite missed it: the fixture `test/Input.svelte` only uses
`let foo` (ambiguous mode, no `export`/no runes), which is one of the few
configurations where `{const}` happens to compile — masking the bug.

### 2. Non-reactive even when it compiles (secondary)

In the ambiguous/runes cases where `{const}` does compile, it emits a plain
once-evaluated binding at the top of the component function. Compiling
`{const v = large ? big : small}` (where `large` is `$state`) yields:

```js
const v = $.get(large) ? big : small;   // read ONCE, outside any effect
$.if(node, ($$render) => { if (typeof v === 'string') ... });  // static v
$.template_effect(() => $.set_attribute(img, 'src', v));       // static v
```

The picture never updates when the source expression depends on reactive state,
unlike the previous inline behavior.

## The fix

Emit a **reactive** `{@const}` instead. Because `{@const}` is only valid as an
immediate child of a block/component, the whole picture is wrapped in an
always-true `{#if true}` block:

```js
if (src_expression) {
  return `{#if true}{@const ${src_var_name} = ${src_expression}}\n${picture}\n{/if}`;
}
return picture;
```

`{@const}` compiles to a `$.derived(...)` (reactive, memoized once-per-update) and
every downstream use becomes `$.get(v)` — restoring reactivity while still
evaluating the expression only once. Crucially, `{@const}` is valid in **both**
legacy and runes mode and has existed since **Svelte 5.0**, so it fixes the
compile error too.

Simple references (`image`, `object.image`) are still inlined
(`should_declare === false`) and are unaffected.

## Bonus: revert the peer-dep bump

Because `{@const}` works on Svelte 5.0, the `svelte` peer-dependency bump to
`^5.56.0` in `packages/enhanced-img/package.json` is no longer needed. The patch
reverts it back to `^5.0.0` (the value prior to commit `1d1bd60`).

## Tests

Updated `test/markup-plugin.spec.js` and the `test/Output.svelte` snapshot to
expect the reactive `{#if true}{@const ...}` wrapping. The `get_image(i)`
single-evaluation assertions still hold.

Co-authored-by: Vercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: teemingc <chewteeming01@gmail.com>
Comment thread packages/enhanced-img/src/vite-plugin.js
@svelte-triage-bot

Copy link
Copy Markdown
Contributor

I investigated this failed test run and found that [chromium-dev] test/cross-platform/client.test.js:179:2 › Navigation lifecycle functions › beforeNavigate prevents navigation triggered by back button is flaky.

The CI failure is unrelated to PR #16900 and is a load-sensitive test synchronization race. A cancelled popstate navigation triggers a compensating history traversal; page.goBack() may resolve before that traversal and the resulting reactive DOM update settle. The test reads the initial 0 false undefined state even though the expected 1 false popstate state follows. Replacing immediate reads with Playwright web-first text and URL assertions fixes the race without reducing coverage. I opened #16945 with a proposed fix.

Rich-Harris pushed a commit that referenced this pull request Aug 26, 2026
Fixes a flaky navigation lifecycle test observed in [PR
#16900](#16900) and [CI run
32992201226](https://github.com/sveltejs/kit/actions/runs/32992201226).

When a popstate navigation is cancelled, SvelteKit performs a
compensating history traversal. `page.goBack()` can resolve before that
traversal and the resulting reactive DOM update have settled, causing
the test to read the initial state. Use Playwright web-first assertions
for both the rendered navigation state and restored URL.

Verification:
- five separate focused runs passed
- 200 dev-mode repeats with four workers passed
- 100 build-mode repeats with four workers passed
- 18 nearby navigation lifecycle tests passed
- full cross-platform client spec passed with one worker (97 tests)

Co-authored-by: svelte-triage-bot <team@svelte.com>
@teemingc
teemingc merged commit d8ed432 into version-3 Aug 26, 2026
72 of 73 checks passed
@teemingc
teemingc deleted the teemingc-avoid-duplicate-function-calls branch August 26, 2026 20:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Don't call functions multiple times

3 participants